<template>
  <ion-page>
    <ion-header>
      <ion-toolbar>
        <ion-searchbar v-model="searchQuery" :debounce="500" @ionInput="handleInput($event)"></ion-searchbar>
      </ion-toolbar>
    </ion-header>
    <ion-content >
      <span>&nbsp;</span>Update at:{{ data }}
        <ion-card class="card" v-for="item in items" :key="item.id" :style="{ backgroundColor: getCardColor(item.triggerTelescopeName) }" >
          <ion-card-header >
            <ion-card-title class="space-between">{{ item.triggerName }}<span class="spacer"></span>{{ item. triggerTelescopeName}}</ion-card-title>            
            <!-- <ion-card-subtitle>Update at:{{ data }}</ion-card-subtitle> -->
          </ion-card-header>        
          <ion-card-content >
            <div class="content">
              <ion-grid >
                <ion-row>
                  <ion-col size="5">EVENT NAME: </ion-col>
                  <ion-col size="7">{{ item.eventName }} 
                    <ion-icon class="eye"  aria-hidden="true" :icon="eyeOutline" button @click="goToDetail(item.triggerName)"/>                
                  </ion-col>
                  <ion-col size="5">TIME:
                    <ion-icon style="font-size: 20px" aria-hidden="true" :icon="helpCircleOutline" button @click="showTooltip1 = true">
                          <ion-popover :is-open="showTooltip1" @didDismiss="showTooltip1 = false" >
                            <ion-header class="bg" ><span>&nbsp;&nbsp;&nbsp;</span>1</ion-header>
                            <ion-content class="ion-padding">Trigger Time(T0),in UT,is retrived from the latest alert packet.</ion-content>
                          </ion-popover>
                         </ion-icon> 
                  </ion-col>
                  <ion-col size="7">{{ item.triggerTime }}</ion-col>
                  <ion-col size="5">REAL: </ion-col>
                  <ion-col size="7" :style="{ color: textColor }">{{ validate(item.validated) }} </ion-col>
                  <ion-col size="5" >RA:
                    <ion-icon style="font-size: 20px" aria-hidden="true" :icon="helpCircleOutline" button @click="showTooltip2 = true">
                          <ion-popover :is-open="showTooltip2" @didDismiss="showTooltip2 = false" >
                            <ion-header class="bg" ><span>&nbsp;&nbsp;&nbsp;</span>2</ion-header>
                            <ion-content class="ion-padding">Coordinates(in J2000 epoch) and Err,are retrived from the latest packet.</ion-content>
                          </ion-popover>
                         </ion-icon>
                  </ion-col>
                  <ion-col  size="7" >{{ item.triggerRaStr }}</ion-col>
                  <ion-col size="5">DEC: </ion-col>
                  <ion-col size="7">{{ item.triggerDecStr }} </ion-col>
                  <ion-col size="5">ERR: 
                    
                  </ion-col>
                  <ion-col size="7">{{ convertToDegMin(item.triggerErr) }} 
                    <select v-model="selectedUnit" >
                      <option v-for="unit in units" :key="unit.value" :value="unit.value" >
                        {{ unit.value }}
                      </option>
                    </select>
                  </ion-col>
                </ion-row>                
               </ion-grid>
            </div>                             
          </ion-card-content>        
      </ion-card>    
    </ion-content>
  </ion-page>
</template>

<script setup >
import { useRouter } from 'vue-router';
const router = useRouter();
import { IonPage,
          IonCard,
          IonPopover,
          IonCardContent,
          IonCardHeader,
          IonIcon,
          IonCardTitle,
          IonGrid, 
          IonCol, 
          IonRow, 
          IonContent,
          IonHeader,
          IonSearchbar,
          IonToolbar
          // IonList,
          //  IonItem,
          } from '@ionic/vue';
import { helpCircleOutline,eyeOutline } from 'ionicons/icons';
import service from '@/api/api'
import { ref } from 'vue';
import { onMounted } from 'vue';
import { onIonViewDidEnter } from '@ionic/vue';
const textColor = ref('red');

const showTooltip1 = ref(false);
const showTooltip2 = ref(false);
const searchQuery = ref('');
const originalItems = ref([]); // 新增：保存原始数据
// const item=[{triggerTelescopeName:'',
//   triggerId:'',
//   eventName: '',
//   triggerName: '',
//   triggerTime: '',
//   triggerRa: '',
//   triggerDec: '',
//   triggerErr: '',
//   validated:'',
//   data:'',
//   id:''}] 
const data=ref('') 
// const items=ref(item)  
const items=ref([])
   const fetchData =async () => {
      try {       
        const response = await service.post('/alertApi/getTriggers',{length:200});
        const response1 = await service.get('/alertApi/getLastTime');
        originalItems.value = response.data.data.list; // 保存原始数据
        items.value = response.data.data.list;
        data.value= response1.data.data;    
        applyFilter(); // 数据更新后应用过滤     
          console.log(response.data);
      } catch (error) {
        // 处理请求错误
        console.error('Error fetching data:',error);
      }
    }    
    onMounted(fetchData);
    
    const goToDetail = (triggerName) => {
      router.push({
      name: 'eventdetails',
      params: { triggerName }, 
    });
  };
 
  const getCardColor = (triggerTelescopeName) => {
  switch (triggerTelescopeName) {
    case 'SVOM':
      return 'Orange';
    case 'LIGO/Virgo':
      return 'Khaki';
    default:
      return 'LightGreen';
  }
};
onMounted(() => {
  setInterval(() => {
    // 刷新页面的逻辑，例如重新请求数据
    doRefresh();
  }, 120000);
  console.log('页面刷新');
});

// 刷新事件处理函数
async function doRefresh() {
  await fetchData(); // 获取最新数据
}

const applyFilter = () => {
  const query = searchQuery.value.toLowerCase();
  items.value = originalItems.value.filter(item =>
    item.triggerName.toLowerCase().includes(query) ||
    item.triggerTelescopeName.toLowerCase().includes(query)
  );
};
const handleInput = (event) => {
  searchQuery.value = event.target.value.toLowerCase();
  applyFilter(); // 输入变化时直接过滤
};

// 页面激活时重新应用过滤
onIonViewDidEnter(() => {
  applyFilter();
});
// const handleInput = (event ) => {
//         console.log('被触发',event)
//         const query = event.target.value.toLowerCase();
//         items.value = items.value.filter((item) =>
//     item.triggerName.toLowerCase().indexOf(query)> -1 || item.triggerTelescopeName.toLowerCase().indexOf(query)> -1);
//     if (searchQuery.value === '') {
//     // 当搜索框为空时，重置列表
//     fetchData();
//   }
// }
const validate = (validated) => {
  if(validated!==null){
    if(validated===true){
      return 'Y';
    }else{
      return 'N';
    }
  }else{
    return '';
  }  
}


const selectedUnit = ref('DEG');
const convertToDegMin = (triggerErr) => {
  const minute=triggerErr*1
  const minutes = triggerErr * 60;
  const minutes1 =triggerErr * 3600;
  if(triggerErr!==null){
    switch (selectedUnit.value) {
    case 'DEG':
      return ` ${minute.toFixed(4)}`;
    case 'MIN':
      return ` ${minutes.toFixed(4)}`;
    default:
      return ` ${minutes1.toFixed(4)}`;
  }
  }
};
  const unit = [
  { value: 'DEG' },
  { value: 'MIN'},
  { value: 'SEC' },
];
const units=ref(unit)
 

// 确保 doRefresh 方法可以在全局访问
window.doRefresh = doRefresh;

</script>

<style scoped>
  .eye{
    background-color:NavajoWhite;
  }
  
  ion-col {
    /* color: #1c1b1b; */
    text-align: start;
  }

 .content{
  background-color: white;
 }
  .card {
  font-family: 'Arial', sans-serif; /* 设置卡片内的字体为Arial */
}
.space-between {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 1.7em;
} 
.spacer {
  width: 50%; 
}
.bg{
  background-color: gold;
}
/* 新增遮罩样式 */
ion-popover::part(backdrop) {
  background: transparent !important; /* 完全透明 */
}



</style>
